<template>
  <div class="p-4 flex-1 overflow-hidden flex flex-col">
    <div>
      <div style="margin-top: -20px;">
        <el-text class="mx-1">
          <span style="color: red;">*</span>上传音频：
        </el-text>
        <el-upload
          :on-change="handleChange"
          v-model:file-list="fileList"
          :limit="1"
          :auto-upload="false"
          style="margin-top: 5px;"
        >
          <template #trigger>
            <el-button>选择文件</el-button>
          </template>
          <div slot="tip" class="el-upload__tip">只能上传 WAV 或 MP3 文件，音频文件范围为3-10秒</div>
        </el-upload>
      </div>
      <div>
        <el-text class="mx-1">
          <span style="color: red;">*</span>参考文本：
        </el-text>

        <div
          style="margin-top: 5px;"
          class="h-10 flex tems-center justify-center rounded text-sm text-gray-900 cursor-pointer"
        >
          <textarea
            style="resize:none;width: 400px;height:100px"
            v-model="prompt_text"
            placeholder="参考文本指的是上传的音频文件的文本"
          ></textarea>
        </div>
      </div>

      <div style="margin-top: 65px;">
        <el-text class="mx-1">
          <span style="color: red;">*</span>文字转语音文案：
        </el-text>

        <div
          style="margin-top: 5px;"
          class="h-10 flex tems-center justify-center rounded text-sm text-gray-900 cursor-pointer"
        >
          <textarea
            style="resize:none;width: 400px;height:100px"
            v-model="mytext"
            placeholder="文字转语音，生成音频内容"
          ></textarea>
        </div>
      </div>
    </div>

    <!-- 语速 -->
    <el-row :gutter="24" style="margin-top:80px;margin-left: -10px;">
      <el-col :span="4">
        <div class="grid-content ep-bg-purple" />
        <div class="centered-container">
          <p style="margin: 0;">语速</p>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content ep-bg-purple" style="width: 100%;">
          <el-slider v-model="speed" :min="0.5" :step="0.5" :max="3" />
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content ep-bg-purple" style="width: 100%;">
          <el-input-number v-model="speed" :min="0.5" :step="0.5" :max="3" />
        </div>
      </el-col>
    </el-row>
    <div>
      <div
        style="background-color: #683CFD;margin-top:10px"
        class="bg-zinc-200 h-10 flex items-center justify-center rounded text-sm text-gray-900 cursor-pointer"
        @click="submitUpload"
      >
        <i style="color: white;" class="iconfont icon-shuaxin2_line mr-2" />
        <span style="color:white;">合成语音</span>
      </div>
    </div>
    <Loading v-show="loading" class="pl-60 bg-opacity-70" />
  </div>
</template>

<script setup lang="ts">
import Loading from "@/components/Loading.vue";
import { usePlayerState } from "@/stores/playerState";
import { useTrackState } from "@/stores/trackState";
import axios from "@/utils/http/request";
import { ElMessage, UploadProps, UploadFile } from "element-plus";
import { ref, Ref } from "vue";

const loading = ref(false);
const mytext = ref("");
const prompt_text = ref("");
const speed = ref("1.0");
//存放上传文件
const fileList = ref([]);

function submitUpload() {
  console.log(fileList.value[0]);
  console.log(prompt_text.value);
  console.log(mytext.value);

  if (mytext.value === "" || mytext.value === null) {
    ElMessage({
      message: "文本不能为空！",
      type: "error"
    });
    return;
  }
  if (fileList.value.length == 0) {
    ElMessage({
      message: "文件不能为空！",
      type: "error"
    });
    return;
  }
  loading.value = true;

  // 使用form表单的数据格式
  const params = new FormData();
  // 将上传文件数组依次添加到参数paramsData中
  console.log(fileList.value[0].raw);
  params.append("file", fileList.value[0].raw);

  // 将输入表单数据添加到params表单中
  params.append("prompt_text", prompt_text.value);
  params.append("text", mytext.value);
  params.append("prompt_language", "zh");
  params.append("text_language", "zh");
  params.append("cut_punc", "");
  params.append("top_k", "15");
  params.append("top_p", "0.9");
  params.append("temperature", "1.0");
  params.append("speed", speed.value);
  params.append("inp_refs", JSON.stringify([]));

  axios
    .post("/api2/voice", params, {
      headers: {
        "Content-Type": "multipart/form-data"
      },
      responseType: "arraybuffer"
    })
    .then(response => {
      ElMessage({
        message: "生成语音成功！",
        type: "success"
      });
      console.log(response);
      var zipName = "voice"; // 下载的文件名
      let blob = new Blob([response.data], { type: "audio/wav" }); // 下载格式为zip
      if ("download" in document.createElement("a")) {
        let elink = document.createElement("a"); // 创建一个<a>标签
        elink.style.display = "none"; // 隐藏标签
        elink.href = window.URL.createObjectURL(blob); // 配置href
        elink.download = zipName;
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 移除<a>标签
      } else {
        // IE10+
        // navigator.msSaveBlob(blob, zipName);
      }

      loading.value = false;
    })
    .catch(error => {
      console.error(error);
      loading.value = false;
    });
}
const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  const allowedTypes = ["audio/wav", "audio/mpeg"];

  // 判断文件类型是否符合要求
  if (!allowedTypes.includes(uploadFile.raw.type)) {
    ElMessage.error("文件格式必须为 WAV 或 MP3!");
    // 阻止文件添加到文件列表中
    const index = uploadFiles.indexOf(uploadFile);
    if (index !== -1) {
      uploadFiles.splice(index, 1);
    }

    return false; // 阻止进一步操作
  }
};
</script>

<style scoped>
.slider-demo-block {
  max-width: 600px;
}

.el-slider {
  margin-top: 20px;
}

.el-slider:first-child {
  margin-top: 0;
}
.centered-container {
  display: flex;
  align-items: left; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}
</style>